import axios from 'axios'

const chatAPI = axios.create({
  baseURL: 'https://api.openai.com/v1',
  headers: {
    'Authorization': `Bearer ${import.meta.env.VITE_OPENAI_API_KEY}`,
    'Content-Type': 'application/json'
  }
})

export const sendMessage = async ({ message, taskId, taskTitle }) => {
  try {
    let prompt = message
    if (taskId && taskTitle) {
      prompt = `关于任务"${taskTitle}"的问题：${message}`
    }

    const response = await chatAPI.post('/chat/completions', {
      model: "gpt-3.5-turbo",
      messages: [{
        role: "system",
        content: taskId ? "你是一个任务沟通助手，帮助用户了解任务详情和要求。" : "你是一个友好的AI助手。"
      }, {
        role: "user",
        content: prompt
      }],
      temperature: 0.7,
      max_tokens: 150
    })
    
    if (response.data && response.data.choices && response.data.choices[0]) {
      return response.data.choices[0].message.content
    } else {
      throw new Error('Invalid response from OpenAI API')
    }
  } catch (error) {
    console.error('Error calling OpenAI API:', error)
    throw error
  }
} 